package com.easy.util;

import cn.hutool.crypto.digest.DigestUtil;

public class PasswordUtil {

    private final static char[] arr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    private final static int salt_index = 5;
    private final static int count_index = 15;

    private final static char FIXED_SALT = 'f';
    private final static int FIXED_COUNT_INDEX = 8;

    public static String encryptPassword(String password) {
        char salt = FIXED_SALT;
        char count = arr[FIXED_COUNT_INDEX];

        String encryptionPassword = password + salt;
        for (int i = 0; i < FIXED_COUNT_INDEX; i++) {
            encryptionPassword = DigestUtil.md5Hex(encryptionPassword);
        }

        StringBuilder strb = new StringBuilder(encryptionPassword);
        strb.insert(salt_index, salt);
        strb.insert(count_index, count);

        return strb.toString();
    }

    // 这个方法一定要在类里
    public static boolean checkPassword(String password, String encryptPassword) {
        if (encryptPassword == null || encryptPassword.length() <= Math.max(salt_index, count_index)) {
            return false;
        }

        try {
            char salt = FIXED_SALT;
            int countIndex = FIXED_COUNT_INDEX;

            String calcPassword = password + salt;
            for (int i = 0; i < countIndex; i++) {
                calcPassword = DigestUtil.md5Hex(calcPassword);
            }

            StringBuilder storedPasswordBuilder = new StringBuilder(encryptPassword);
            storedPasswordBuilder.deleteCharAt(count_index);
            storedPasswordBuilder.deleteCharAt(salt_index);
            String storedPassword = storedPasswordBuilder.toString();

            return calcPassword.equals(storedPassword);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
